package com.wisnews.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * @Description：使用foxmail发送邮件
 * @Author: yuyd
 * @Email: yyd8358@foxmail.com
 * @Date: 2020/12/24 14:33
 * @Version 1.0
 */
@Service("sendEmail")
@Slf4j
public class QQEmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 配置文件中我的邮箱
     */
    @Value("${spring.mail.from}")
    private String from;

    /**
    *
    *  异步发送邮件
    *接口中标注了@Asyn 单独新建一个线程去发送邮件
    * */
    @Async
    public void sendSimpleMail(String to, String subject, String content) throws MailException {

            if (StringUtils.isBlank(to)){
                return;
            }

           SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
           //邮件发送人
           simpleMailMessage.setFrom(from);
           //发送给谁
           simpleMailMessage.setTo(to);
           //设置邮箱主题
           simpleMailMessage.setSubject(subject);
           //设置邮箱内容
           simpleMailMessage.setText(content);

           javaMailSender.send(simpleMailMessage);

           log.info("sendSimpleMail==>发送邮件给 "+to+" 成功");
    }


    @Async
    public void sendHtmlMail(String to, String subject, String content) throws MailException {

        MimeMessage message=javaMailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            javaMailSender.send(message);
            log.info("sendHtmlMail==>发送html格式邮件 "+to+" 成功");
        }catch (Exception e){
            log.info("sendHtmlMail==>html格式邮件发送失败");
        }
    }

}
